package xuan.gui;

import javax.swing.JFileChooser;

import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import xuan.lib.*;

@SuppressWarnings("serial")
public class DemoMain extends JFrame implements ActionListener{	
	private OpenFileWindow openFileWindow = null;
	private InteractiveMergePanel panel =null;
	
	private JMenuItem mnOpen = new JMenuItem("open");;
	private JMenuItem mnSave = new JMenuItem("save");
	private JMenuItem mnQuit = new JMenuItem("quit");
	private final JMenu mnOperation = new JMenu("Operation");
	private final JMenuItem mnUndo = new JMenuItem("Undo");
	private final JMenuItem mnConfirm = new JMenuItem("ConfirmDefinitively");
	private final JMenuItem mnReload = new JMenuItem("reload");
	
	
	public DemoMain() {
		
		panel = new InteractiveMergePanel(this);
		getContentPane().add(panel, "Center");
		
		JMenuBar menuBar = new JMenuBar();
		 setJMenuBar(menuBar);
		
		JMenu mnFiles = new JMenu("File");
		menuBar.add(mnFiles);
	
		mnFiles.add(mnOpen);
		mnOpen.addActionListener(this);
		
		mnFiles.add(mnSave);
		mnSave.addActionListener(this);
		
		mnFiles.add(mnReload);
		mnReload.addActionListener(this);
		
		mnFiles.add(mnQuit);
		mnQuit.addActionListener(this);
		
		menuBar.add(mnOperation);
		
		mnOperation.add(mnUndo);
		mnUndo.addActionListener(this);
		
		mnOperation.add(mnConfirm);
		
		JMenu menu = new JMenu("?");
		menuBar.add(menu);
		
		pack();
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setTitle("3dm merging");
		setLocationRelativeTo(null);
		setVisible(true);
	}


	public void actionPerformed(ActionEvent evt) {
		Object evtSource = evt.getSource();
	    if (evtSource == mnOpen) {
	    	openFileWindow = new OpenFileWindow(this);
	        Transfer transfer = new Transfer();
	    	if (openFileWindow.showDialog(transfer)) {
	    		panel.removeAll();	    		
	    		panel.load(transfer.getValue());
	    	}
	    }
	    if(evtSource == mnSave){
	    	JFileChooser chooser = new JFileChooser();
	    	chooser.showSaveDialog(this);
	    	try{
				String fileName = chooser.getSelectedFile().getAbsolutePath();
				panel.save(fileName);
				JOptionPane.showMessageDialog(this, "file is saved");
			}
			catch(Exception e){}
	    }
	    if(evtSource == mnReload){
	    	panel.removeAll();	    		
    		panel.load(null);
	    }
	    if(evtSource == mnQuit){ 
	    	System.exit(0);
	    }
	    if(evtSource == mnUndo){
	    	panel.undo();
	    }
	}
	
	
	public static void main(String[] args) {
		new DemoMain();	    
	}
}
